// // 获取当前日期并设置为早上 9 点
// const currentDate = new Date();
// currentDate.setHours(9, 0, 0, 0);
// const formattedDate = currentDate.toISOString().split('T')[0];
//
// // 设置两个日期输入框的默认值为当天早上 9 点
// document.getElementById('date1').value = formattedDate;
// document.getElementById('date2').value = formattedDate;

// 计算大门票总价
document.getElementById('bookGateForm').addEventListener('input', function () {
    const quantity = document.getElementById('quantity1').value;
    const totalPriceInput = document.getElementById('totalPrice1');
    totalPriceInput.value = quantity * 40;
});

// 计算馆中馆门票总价
function calculateExhibitionTotal() {
    const quantity = document.getElementById('quantity2').value;
    const typeSelect = document.getElementById('type1');
    const selectedType = typeSelect.value;
    let totalPrice = 0;
    if (selectedType === 'EXHIBITION1') {
        totalPrice = quantity * 20;
    } else if (selectedType === 'EXHIBITION2') {
        totalPrice = quantity * 30;

    } else if (selectedType === 'EXHIBITION1_AND_2') {
        totalPrice = quantity * 45;

    }
    document.getElementById('totalPrice2').value = totalPrice;
}




//购买大门票
document.getElementById('bookGateForm').addEventListener('submit', function (event) {
    event.preventDefault();

    const userId = parseInt(document.getElementById('userId1').value);
    const quantity = parseInt(document.getElementById('quantity1').value);
    const date = document.getElementById('date1').value;

    // 假设大门票单价为 40
    const pricePerTicket = 40;
    const totalPrice = quantity * pricePerTicket;

    document.getElementById('totalPrice1').value = totalPrice;

    fetch('/api/book/gate', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams({
            userId: userId,
            quantity: quantity,
            totalPrice: totalPrice,
            date: date
        })
    })
        .then(response => {
            if (!response.ok) {
                return response.text().then(text => {
                    throw new Error(text);
                });
            }
            return response.json();
        })
        .then(data => {
            alert('预订成功！');
        })
        .catch(error => {
            alert('预订失败：' + error.message);
        });
});

//购买馆中馆门票
document.getElementById('bookExhibitionForm').addEventListener('submit', function (event) {
    event.preventDefault();

    const userId = parseInt(document.getElementById('userId2').value);
    const quantity = parseInt(document.getElementById('quantity2').value);
    const ticketType = document.getElementById('type1').value; // 获取票种
    const date = document.getElementById('date2').value;

    // 根据票种设置单价
    let pricePerTicket;
    switch (ticketType) {
        case 'EXHIBITION1':
            pricePerTicket = 20;
            break;
        case 'EXHIBITION2':
            pricePerTicket = 30;
            break;
        case 'EXHIBITION1_AND_2':
            pricePerTicket = 45;
            break;
        default:
            alert('请选择有效的票种！');
            return;
    }

    const totalPrice = quantity * pricePerTicket;

    document.getElementById('totalPrice2').value = totalPrice;

    // 格式化日期
    const formattedDate = new Date(date).toISOString().split('T')[0];

    fetch('/api/book/exhibition', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams({
            userId: userId,
            type: ticketType,  // 添加 type 参数
            quantity: quantity,
            totalPrice: totalPrice,
            date: formattedDate
        })
    })
        .then(response => {
            if (!response.ok) {
                return response.text().then(text => {
                    throw new Error(text);
                });
            }
            return response.json();
        })
        .then(data => {
            alert('预订成功！');
        })
        .catch(error => {
            alert('预订失败：' + error.message);
        });
});



//查询订票记录
document.getElementById('getBookingRecordsForm').addEventListener('submit', function (e) {
    e.preventDefault();
    const userId = document.getElementById('userId').value;
    fetch(`/api/booking-records/${userId}`)
        .then(response => response.json())
        .then(data => {
            console.log(data);
            const tableBody = document.getElementById('bookingRecordsTable').getElementsByTagName('tbody')[0];
            tableBody.innerHTML = '';
            data.forEach(order => {
                const row = tableBody.insertRow();
                row.insertCell(0).textContent = order.orderId;
                row.insertCell(1).textContent = userId;
                row.insertCell(2).textContent = order.ticketId;
                row.insertCell(3).textContent = order.quantity;
                row.insertCell(4).textContent = order.totalPrice;
                row.insertCell(5).textContent = order.status;
                row.insertCell(6).textContent = order.date;

            });
        })
        .catch(error => console.error('Error fetching booking records:', error));
});

//退票
document.getElementById('refundForm').addEventListener('submit', function (e) {
    e.preventDefault();
    const orderId = document.getElementById('orderId').value;
    fetch(`/api/refund/${orderId}`, {
        method: 'PUT'
    })
        .then(response => response.text())
        .then(message => {
            alert(message);
        })
        .catch(error => {
            console.error('Error during refund:', error);
            alert('退票过程中出现错误');
        });
});

//查询余量
document.getElementById('getDailyRemainingTicketsForm').addEventListener('submit', function (event) {
    event.preventDefault();
    const typeSelect = document.getElementById('type2');
    const selectedType = typeSelect.value;
    fetch('/api/daily-remaining/' + selectedType)
        .then(response => response.json())
        .then(data => {
            // 确保 data 是一个整数，如果不是，进行适当的处理
            if (typeof data === 'number') {
                const remainingTicketsElement = document.getElementById('remainingTickets');
                remainingTicketsElement.textContent = '余量：' + data;
            } else {
                // 处理非整数情况，例如显示错误信息
                remainingTicketsElement.textContent = '获取余量失败';
            }
        })
        .catch(error => console.error('Error fetching remaining tickets:', error));
});
